﻿using Common;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using SystemEntity;
using SystemRepository;

namespace SystemService
{
    public class SystemUrlService : IScoped
    {
        private readonly ILogger<SystemUrlService> _logger;

        private UrlRepository _urlRepository = null;
        public SystemUrlService(UrlRepository urlRepository, ILogger<SystemUrlService> logger)
        {
            _logger = logger;
            _urlRepository = urlRepository;
        }

        public void CheckAndAdd(SystemUrlEntity urlEntity) 
        {
           List<SystemUrlEntity> urlList = _urlRepository.GetByWhere(t => t.Url == urlEntity.Url);
            if (urlList==null || urlList.Count==0)
            {
                _urlRepository.Insert(urlEntity);
            }
            else
            {
                UpdateUrlInfo(urlEntity);
            }
        }
        public void UpdateUrlInfo(SystemUrlEntity urlEntity) 
        {
            SystemUrlEntity newurlEntity = _urlRepository.FirstOrDefault(t => t.Url == urlEntity.Url);
            newurlEntity.LastCallTime = DateTimeOffset.Now.UtcTicks;
            newurlEntity.CallTimes = urlEntity.CallTimes++;
            newurlEntity.Name = urlEntity.Name;
            newurlEntity.ApplicationName = urlEntity.ApplicationName;
            newurlEntity.ControllerName = urlEntity.ControllerName;
            _urlRepository.Update(newurlEntity);
        }
    }
}
